package tmi.li.txwidgets.txwthr;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.

import tmi.li.txwidgets.ColorPickerDialog;
import tmi.li.txwidgets.R;
import tmi.li.txwidgets.TxWidgetsFinals;



public class TxWthrConfiguration extends Activity implements Runnable {
	public Woeid w = new Woeid();
	private ProgressDialog pd;
	private TxWthrWidget widget;
	private CharSequence[] appNames;
	private long timestamp;
	private String city;
	private TextView text;
	private Thread thread;
	private Dialog currentDialog;
	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

	
	public TxWthrConfiguration() {
		super();
	}

	
	@Override
	public void onCreate(Bundle icicle) {
		
		super.onCreate(icicle);

		
		// Set the result to CANCELED.  This will cause the widget host to cancel
		// out of the widget placement if they press the back button.
		setResult(RESULT_CANCELED);
		// Set the view layout resource to use.
		setContentView(R.layout.txwthr_config);

		//fill the SPinner with the languages
		Spinner s = (Spinner) findViewById(R.id.sLanguage);
		@SuppressWarnings("rawtypes")
		ArrayAdapter adapter = ArrayAdapter.createFromResource(
	            this, R.array.lang, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    s.setAdapter(adapter);
	    
	    s = (Spinner) findViewById(R.id.sFormat);
		@SuppressWarnings("rawtypes")
		ArrayAdapter adapter2 = ArrayAdapter.createFromResource(
	            this, R.array.format_temp, android.R.layout.simple_spinner_item);
	    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    s.setAdapter(adapter2);
		
	    
	    
	    //COLOR
        TextView ed = (TextView)findViewById(R.id.tFLColor);
        ed.setOnClickListener(openColorDialog);
        ed = (TextView)findViewById(R.id.tFTColor);
        ed.setOnClickListener(openColorDialog);
        ed = (TextView)findViewById(R.id.tFBColor);
        ed.setOnClickListener(openColorDialog);
        ed = (TextView)findViewById(R.id.tBColor);
        ed.setOnClickListener(openColorDialog);
	    
	    
		// Bind the action for the save button.
	    findViewById(R.id.bAppName).setOnClickListener(mAppClickListener);
		findViewById(R.id.bSave).setOnClickListener(mSaveOnClickListener);
		findViewById(R.id.bWoeid).setOnClickListener(mCityOnClickListener);
		
		
		// Find the widget id from the intent. 
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		if (extras != null) {
			mAppWidgetId = extras.getInt(
					AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
		}

		// If they gave us an intent without the widget id, just bail.
		if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}
		
		widget = new TxWthrWidget(getBaseContext());
		widget._id = mAppWidgetId;
		widget._format = "c";
		
	}
	//menu dialog for picking a app
	public void openAppMenu() {
		//IntentCategorys
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);;
		//Init Lists
		@SuppressWarnings("rawtypes")
		final List AppList = getPackageManager().queryIntentActivities(mainIntent, 0);
		//final CharSequence[] appPackageNames = new CharSequence[AppList.size()];
		appNames = new CharSequence[AppList.size()+2];
		appNames[0] = "none";
		appNames[1] = "update Weather";
		final ResolveInfo[] appInfos =  new ResolveInfo[AppList.size()+2];
		int i = 2;
		//Get appnames and packagenames
		for (Object item:  getPackageManager().queryIntentActivities( mainIntent, 0)) {
			appInfos[i] = (ResolveInfo)item;
			appNames[i] = getPackageManager().getApplicationLabel(appInfos[i].activityInfo.applicationInfo);
			i++;
		}

		//Create dialog.builder
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pick a app");
		builder.setItems(appNames, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				text = (TextView)findViewById(R.id.tAppName);
				text.setText(appNames[item]);	
				if(item == 0) {
					widget._appname = null;
				}else if(item == 1) {
					widget._appname = "update";
				}else {
					Toast.makeText(getApplicationContext(), "selected App: "+appNames[item], Toast.LENGTH_SHORT).show();	
					widget._appname = appInfos[item].activityInfo.packageName.toString()+"/"+appInfos[item].activityInfo.name.toString();
				}
							
			}
		});

		//Create dialog with builder
		AlertDialog alert = builder.create();

		//Display dialog
		alert.show();
	}

	
	//menu dialog for picking a city
	public void openMenu() {
		if(w._woeid != null && w._woeid.size() > 0) {
			int length = w._woeid.size();
			
			
			//if only one city was found, end it without opening a menu
			if(length == 1) {
				widget._woeid = w._woeid.get(0).split(",")[0];
				text = (TextView)findViewById(R.id.tCity);
				text.setText(w._woeid.get(0)+ ", "+ w.getDesc(0));
				
				
			}else if(length > 1){ // if more then one city was found, fill a array with city name + country 
				final CharSequence[] items = new CharSequence[length];
				for(int i = 0; i < length; i++) {
					items[i] = w.getDesc(i);
				}
				
				//Initialize the Menu and implement the onclicklistener
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Pick the most likely result");
				builder.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {		 
						Toast.makeText(getApplicationContext(), "selected: "+items[item], Toast.LENGTH_SHORT).show();
						text = (TextView)findViewById(R.id.tCity);
						text.setText(city);
						widget._woeid = w._woeid.get(item);
					}
				});
				AlertDialog alert = builder.create();
				alert.show();
			}else {
				//set current dialog to new custom dialog
				currentDialog = new Dialog(this);

				//set content view and title
				currentDialog.setContentView(R.layout.customwoeid_dialog);
				currentDialog.setTitle("No city found - Please add woeid");

				//register events on both buttons
				currentDialog.findViewById(R.id.bSaveWoeID).setOnClickListener(mCityCodeSaveOnClickListener);
				currentDialog.findViewById(R.id.bCancelWoeID).setOnClickListener(mCityCodeCancelOnClickListener);
				
				//and finally show dialog to user
				currentDialog.show();
			}
		}else {
			//same again only if woeid object is null ... because of exception or offline client?!
			//set current dialog to new custom dialog
			currentDialog = new Dialog(this);

			//set content view and title
			currentDialog.setContentView(R.layout.customwoeid_dialog);
			currentDialog.setTitle("No city found - Please add woeid");

			//register events on both buttons
			currentDialog.findViewById(R.id.bSaveWoeID).setOnClickListener(mCityCodeSaveOnClickListener);
			currentDialog.findViewById(R.id.bCancelWoeID).setOnClickListener(mCityCodeCancelOnClickListener);
			
			//and finally show dialog to user
			currentDialog.show();
		}
	}


	//onclick listener for getWoeid button
	View.OnClickListener mCityOnClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			//saving the city name in the var city & starting the thread 
			EditText ecity = (EditText)findViewById(R.id.eWoeid);
			city = ecity.getText().toString();
			thread = new Thread(TxWthrConfiguration.this);
			pd = ProgressDialog.show(TxWthrConfiguration.this, "Loading..", "Getting Woeid for "+city, true,false);	
			try { 
				thread.start();   
			}catch(Exception e) {
				pd.dismiss();
				Toast.makeText(getApplicationContext(), "Error occured, try again", Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	View.OnClickListener mCityCodeSaveOnClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			//get EditText from dialog
			EditText ecity = (EditText)currentDialog.findViewById(R.id.eWoeID);
			try{
				//try to parse the input to long
				long woeid = Long.parseLong(ecity.getText().toString());
				
				//set textview -> configuration activity
				text = (TextView)findViewById(R.id.tCity);
				text.setText("Own Woeid: " + woeid);
				
				//save woeid to widget object
				city = ecity.getText().toString();
				widget._woeid = String.valueOf(woeid);
				
				//clear edittext -> configuration activity
				((EditText)findViewById(R.id.eWoeid)).setText("");
				
				//toast that woe where added
				Toast.makeText(getApplicationContext(), "added own woeid: "+woeid, Toast.LENGTH_SHORT).show();
				
				//hide dialog
				currentDialog.hide();
			}catch(NumberFormatException ex){
				//if parse to long runs into exception
				Toast.makeText(getApplicationContext(), "Please only numbers...", Toast.LENGTH_SHORT).show();
			}
			catch(Exception ex){
				//only on fatal error, toast it and hide dialog
				Toast.makeText(getApplicationContext(), "Error occured, try again", Toast.LENGTH_SHORT).show();
				currentDialog.hide();
			}
		}
	};
	View.OnClickListener mCityCodeCancelOnClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			//hide dialog......
			currentDialog.hide();
		}
	};

	//onclick listener for AppSelector DIalog
	View.OnClickListener mAppClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			//final Context context = AppWidgetConfigure.this;
			//saving the city name in the var city & starting the thread 
			openAppMenu();
		}
	};
	
	//onclick Listener for the save Dialog
	View.OnClickListener mSaveOnClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			final Context context = TxWthrConfiguration.this;
						
			//if no city was selected notificate the user
			if(widget._woeid != "") {
				try { 
					

					
					//returning the result
					Intent resultValue = new Intent();
					resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
					setResult(RESULT_OK, resultValue);
					
					
					//saving the languages
					widget._lang = specLang((String)((Spinner) findViewById(R.id.sLanguage)).getSelectedItem());
					
					String test = (String)((Spinner)findViewById(R.id.sFormat)).getSelectedItem();
					if(test.contains("F")) {
						widget._format = "f";
					}else {
						widget._format = "c";
					}
					
					
					
					//COLORS
					widget._flcolor = ((EditText)findViewById(R.id.eFLColor)).getText().toString();
					widget._ftcolor = ((EditText)findViewById(R.id.eFTColor)).getText().toString();
					widget._fbcolor = ((EditText)findViewById(R.id.eFBColor)).getText().toString();
					widget._bcolor = ((EditText)findViewById(R.id.eBColor)).getText().toString();
					

					widget.save();
					Intent intent = new Intent(TxWidgetsFinals.TXWTHR_BUILD_UPDATE);
					context.sendBroadcast(intent);
					
					thread = null;
					finish();
				}catch(Exception e) {
					e.printStackTrace();
					Toast.makeText(getApplicationContext(), "Wrong Color code !!", Toast.LENGTH_LONG).show();
				}
			}else {
				Toast.makeText(getApplicationContext(), "No City selected !!", Toast.LENGTH_LONG).show();
			}

		}
	};
	
	View.OnClickListener openColorDialog = new View.OnClickListener() {

		public void onClick(View v) {
			final int ids = v.getId();
			final ColorPickerDialog clr = new ColorPickerDialog(v.getContext());
			clr.onSaveClicked = new View.OnClickListener() {

				public void onClick(View v) {
					EditText ed = (EditText)findViewById(ids-1);
					ed.setText(clr.getColorHex());
					TextView view = (TextView)findViewById(ids);
					view.setBackgroundColor(clr.getColor());
					clr.dismiss();
				}
			};
			clr.show();
		}
	};

	
	//getting the right Lang String
	public String specLang(String lang) {
		if(compareString(lang, "Eng"))
			return "en";
		if(compareString(lang, "Fre"))
			return "fr";
		if(compareString(lang, "Ru"))
			return "ru";
		if(compareString(lang, "Ger"))
			return "de";
		if(compareString(lang, "Ita"))
			return "it";
		if(compareString(lang, "Dan"))
			return "da_DK";
		if(compareString(lang, "Dut"))
			return "nl_BE";
		if(compareString(lang, "Spani"))
			return "es";
		if(compareString(lang, "Portu"))
			return "pt";
		if(compareString(lang, "Croat"))
			return "hr";
		return "null";
	}
	
	public boolean compareString(String orig, String cmp) {
		int orig_size = orig.length();
		int cmp_size = cmp.length();
		String orig_up = orig.toLowerCase();
		String orig_down = orig.toUpperCase();
		int b = 0;
		for(int i = 0; i < orig_size; i++) {
			if(orig.charAt(i) == cmp.charAt(b) || orig_up.charAt(i) == cmp.charAt(b) || orig_down.charAt(i) == cmp.charAt(b)) {
				b++;
				if(b == cmp_size)return true;
				continue;
			}
			else {
				if(orig_size - i < cmp_size) return false;
				if(b != 0) b = 0;
				continue;
			}
			
		}
		
		return false;
		
	}
	
	
	
	//the Thread used for getting the woeid
	//thread tries every second to get the woeid until 15 seconds
	//then the thread will break and the user will get the message that no wifi connection
	//could be established
	
	public void run() {
		boolean t = false; 
		//timestamp when we first try to get the woeid
		timestamp = System.currentTimeMillis();
		
		//try and try and try...
		while(!t) {
			if(t = w.getRss(city)) {
				//if the getRss was successful break the loop and send a message to the handler
				handler.sendEmptyMessage(0);	
				break;
			}
			//set the thread to sleep 1 second
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				handler.sendEmptyMessage(1);	
			}
			
			//if 15 seconds did pass without getting the woeid once, break the loop and send a message to the handler
			if(System.currentTimeMillis() - timestamp > 20000){
				handler.sendEmptyMessage(1);	
				break;
			}
		}
	}

	//handler used to notify user when thread was successful 
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			//if thread was successful then dismiss the progress dialog and open the menu
			if(!msg.equals(1)) 	{
				pd.dismiss();
				openMenu();
				
				//FIXME
				try {
					thread = null;
				}catch(Exception e) {
					Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
				}
				
			}else { // notify the user that no connection could be established
					Toast.makeText(getApplicationContext(), "Couldnt connect to Woeid webservice", Toast.LENGTH_LONG).show();
			}
		}
	};    

}